from PyQt6.QtCore import QSettings,Qt
from PyQt6.QtWidgets import QMainWindow, QTableWidgetItem,QFileDialog

from httpApi.httpApi import HttpApi
from ui_py.mainUI import Ui_MainWindow
from ui_py.devicelistUI import Device_Func
from .deviceListController import DeviceListController


# 主界面
class HomeMainController(QMainWindow, Ui_MainWindow):

    def __init__(self):
        super(HomeMainController, self).__init__()
        self.setupUi(self)
        self.retranslateUi(self)
        self.settings = QSettings("userInfo")
        self.listData = []
        self.fileMenu = self.menubar.addMenu('&文件')
        self.optionsMenu = self.menubar.addMenu('&选择')
        self.seesMenu = self.menubar.addMenu('&查看')
        self.helpMenu = self.menubar.addMenu('&帮助')
        self.statusBar().showMessage(self.currentdates.toString(Qt.DateFormat.ISODate))
        self.creatInit()
        self.creatData()

    def creatInit(self):
        self.tableWidget.horizontalHeader().setStretchLastSection(True)
        self.logoutButton.clicked.connect(self.logoutClick)
        self.update_pro_device_infoButton.clicked.connect(self.show_excel_dialog)
        pass

    def logoutClick(self):
        print("跳转")

    def show_excel_dialog(self):
        fname = QFileDialog.getOpenFileName(
            self,
            "Open File",
            "${HOME}",
            "All Files (*);; Python Files (*.py);; PNG Files (*.png)",
        )
        print(fname)
        # try:
        #     # 使用 QFileDialog 获取 Excel 文件的路径
        #     options = QFileDialog.o
        #     options |= QFileDialog.Option.ReadOnly  # 只读模式
        #     options |= QFileDialog.Option.DontUseNativeDialog  # 使用 QFileDialog 而不是系统原生对话框

        #     file_dialog = QFileDialog(self, options=options)
        #     file_dialog.setNameFilter("Excel 文件 (*.xlsx *.xls)")
        #     file_dialog.setDefaultSuffix("xlsx")

        #     # 获取选中的文件路径
        #     file_path, _ = file_dialog.getOpenFileName(self, "选择Excel文件", "", "Excel 文件 (*.xlsx *.xls)")

        #     if file_path:
        #         print("选择的Excel文件路径:", file_path)
        #         # 在这里你可以处理文件路径，进行进一步的操作

        # except Exception as e:
        #     print("Error:", e)

    def creatData(self):
        json_data = {
            "username": "jujikj@jj.com",
            "password": "1234Juji"
        }
        HttpApi().requestPost(url="http://om.jujiembs.com/api/auth/login", data=json_data, callback=lambda value: {
            self.getUserInfo(value)
        })
    def getUserInfo(self, value):
        self.settings.setValue("token", f"Bearer {value['token']}")
        HttpApi().requestGet(url="http://om.jujiembs.com/api/auth/user",
                             callback=lambda value: {
                                 self.getListWithGateway(value)
                             })


    def getListWithGateway(self, value):
        customerId = value["customerId"]["id"]
        HttpApi().requestGet(
            url=f"http://om.jujiembs.com/api/customer/{customerId}/deviceInfos?pageSize=100&page=0&sortProperty=createdTime&sortOrder=DESC",
            callback=lambda value: {
                self.updateUI(value)
            })
        
        pass

    def updateUI(self, mapdata):
        self.listData = mapdata["data"]
        self.tableWidget.setRowCount(len(self.listData))
        for i in range(len(self.listData)):
            self.tableWidget.setItem(i, 0, QTableWidgetItem(self.listData[i]["name"]))
            self.tableWidget.setItem(i, 1, QTableWidgetItem(self.listData[i]["label"]))
            self.tableWidget.setItem(i, 2, QTableWidgetItem(str(self.listData[i]["active"])))
            self.tableWidget.setItem(i, 3, QTableWidgetItem("更多"))
        # 设置单元格自动换行
        self.tableWidget.setWordWrap(True)
        # 设置自适应宽度
        self.tableWidget.resizeColumnsToContents()
        self.tableWidget.clicked.connect(self.clickRow)
        
    
    # 点击列表
    def clickRow(self,item):
        row = item.row()
        col = item.column()
        #检查列表展示不同页面
        if col == 0:
            self.devicelistpage = DeviceListController(self.listData[self.tableWidget.currentRow()])
            self.devicelistpage.show()
        if col == 3:
            self.device_func = Device_Func(self.listData[row])
            self.device_func.show()
            pass
    
